#include	"IA.hh"

IA::IA(char *srv_addr, int port)
{
  if (!(this->socket.createSocket()))
    std::cerr << "Unable to create socket" << std::endl;
  if (!(this->socket.connectSocket(srv_addr, port)))
    {
      std::cerr << "Unable to reach distant server" << std::endl;
      exit(-1);
    }
  if (!(this->inBuffer = (char *)malloc(4096)))
    {
      std::cerr << "Cannot allocate a proper buffer" << std::endl;
      exit(-1);
    }
  memset(this->inBuffer, 0, 4096);
}

IA::~IA(void)
{
  this->socket.closeSocket();
}

bool		IA::discoverServer(void)
{
  if ((this->socket.writeSocket(DISCOVER.c_str(), DISCOVER.length())) == -1)
    return false;
  while (!(strchr(this->inBuffer, '\n')))
    if ((this->socket.readSocket(this->inBuffer, 4096)) < 0)
      return false;
  std::cout << '[' << this->inBuffer << ']' << std::endl;
  this->rules.parseRules(this->inBuffer);
  std::cout << "Double3: " << this->rules.getThrees() <<
    " Breaking5: " << this->rules.getFives() <<
    " Ms: " << this->rules.getMs() << std::endl;
  return true;
}
